﻿using MyMes.Infrastructure;
using MyMES.Dto;
using MyMES.IServices.QualityAssurance;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using VOL.Entity.DomainModels.Core;
using VOL.Entity.DomainModels.QualityAssurance;
using VOL.Core.Utilities.Response;
using Microsoft.EntityFrameworkCore;
using VOL.Core.Extensions;
using VOL.Entity.DomainModels;
using MaterialCatalog = VOL.Entity.DomainModels.QualityAssurance.MaterialCatalog;

namespace MyMES.Services.QualityAssurance
{
    public class OutProductCheckService : IOutProductCheckService
    {
        private readonly IBaseRepository<OutProductCheck> _outProductCheckRepository;
        private readonly IBaseRepository<Customer> _customerRepository;
        private readonly IBaseRepository<MaterialProduct> _materialProductRepository;
        private readonly IBaseRepository<MaterialCatalog> _materialCatalogRepository;

        public OutProductCheckService(IBaseRepository<OutProductCheck> outProductCheckRepository, IBaseRepository<Customer> customerRepository, IBaseRepository<MaterialProduct> materialProductRepository, IBaseRepository<MaterialCatalog> materialCatalogRepository)
        {
            _outProductCheckRepository = outProductCheckRepository;
            _customerRepository = customerRepository;
            _materialProductRepository = materialProductRepository;
            _materialCatalogRepository = materialCatalogRepository;
        }

        /// <summary>
        /// 添加出货检查记录
        /// </summary>
        /// <param name="outProductCheck">出货检查记录实体</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> AddOutProductCheck(OutProductCheck outProductCheck)
        {
            WebResponseContent response = new WebResponseContent();

            try
            {

                // 添加记录
                await _outProductCheckRepository.AddAsync(outProductCheck);

                return response.OK($"添加出货检查记录成功，检验编码：{outProductCheck.CheckCode}", outProductCheck);
            }
            catch (Exception ex)
            {
                return response.Error($"添加出货检查记录失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 删除出货检查记录
        /// </summary>
        /// <param name="ids">记录ID列表，逗号分隔</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> DelOutProductCheck(string ids)
        {
            WebResponseContent response = new WebResponseContent();

            try
            {


                // 分割ID字符串
                string[] idArray = ids.Split(',');
                List<int> idList = new List<int>();
                
                foreach (var id in idArray)
                {
                    if (int.TryParse(id, out int parsedId))
                    {
                        idList.Add(parsedId);
                    }
                }

                // 删除记录
                await _outProductCheckRepository.DelAll(o => idList.Contains(o.Id));

                return response.OK("删除成功", null);
            }
            catch (Exception ex)
            {
                return response.Error($"删除出货检查记录失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 获取出货检查记录列表
        /// </summary>
        /// <param name="dto">查询条件</param>
        /// <returns>分页数据</returns>
        public async Task<PageGridData<OutProductCheckDto>> GetOutProductCheckList(GetOutProductCheckDto dto)
        {
            PageGridData<OutProductCheckDto> pageGridData = new PageGridData<OutProductCheckDto>();

            try
            {
                // 三表联查：出货检查表、物料产品表和客户表
                var query = from check in _outProductCheckRepository.GetAll()
                            join material in _materialProductRepository.GetAll()
                            on check.ProductCode equals material.MaterialCode 
                            join customer in _customerRepository.GetAll()
                            on check.CustomerCode equals customer.CustCode 
                            select new OutProductCheckDto
                            {
                                Id = check.Id,
                                CheckCode = check.CheckCode,
                                CheckName = check.CheckName,
                                Batch = check.Batch,
                                ProductCode = check.ProductCode,
                                OutNum = check.OutNum,
                                CheckNum = check.CheckNum,
                                LowNum = check.LowNum,
                                CheckResult = check.CheckResult,
                                CustomerCode = check.CustomerCode,
                                OutDate = check.OutDate,
                                CheckDate = check.CheckDate,
                                Descs = check.Descs,
                                // 关联物料表的字段
                                MaterailName =  material.MaterialName ,
                                Size =material.Specification ,
                                // 关联客户表的字段
                                CustomerName = customer.CustName
                            };

                // 应用查询条件
                query = query.WhereIF(!string.IsNullOrEmpty(dto.CheckCode), o => o.CheckCode.Contains(dto.CheckCode))
                             .WhereIF(!string.IsNullOrEmpty(dto.Batch), o => o.Batch.Contains(dto.Batch))
                             .WhereIF(!string.IsNullOrEmpty(dto.MaterailCode), o => o.ProductCode.Contains(dto.MaterailCode))
                             .WhereIF(!string.IsNullOrEmpty(dto.MaterailName), o => o.MaterailName.Contains(dto.MaterailName))
                             .WhereIF(!string.IsNullOrEmpty(dto.CustomerName), o => o.CustomerName.Contains(dto.CustomerName))
                             .WhereIF(!string.IsNullOrEmpty(dto.CheckResult), o => o.CheckResult.Contains(dto.CheckResult));

                // 获取总记录数
                var count = await query.CountAsync();

                // 分页
                var data = await query.OrderByDescending(o => o.CheckDate)
                                      .Skip((dto.PageIndex - 1) * dto.PageSize)
                                      .Take(dto.PageSize)
                                      .ToListAsync();

                // 构建返回数据
                pageGridData.rows = data;
                pageGridData.total = count;

                return pageGridData;
            }
            catch (Exception ex)
            {
                pageGridData.rows = new List<OutProductCheckDto>();
                pageGridData.total = 0;
                pageGridData.summary = $"获取出货检查记录失败：{ex.Message}";
                return pageGridData;
            }
        }

        /// <summary>
        /// 更新出货检查记录
        /// </summary>
        /// <param name="outProductCheck">更新后的记录</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> UpdOutProductCheck(OutProductCheck outProductCheck)
        {
            WebResponseContent response = new WebResponseContent();

            try
            {

                // 更新记录
                await _outProductCheckRepository.UpdateAsync(outProductCheck);

                return response.OK($"更新出货检查记录成功，检验编码：{outProductCheck.CheckCode}", outProductCheck);
            }
            catch (Exception ex)
            {
                return response.Error($"更新出货检查记录失败：{ex.Message}");
            }
        }
        
        /// <summary>
        /// 获取客户列表
        /// </summary>
        /// <param name="dto">查询条件</param>
        /// <returns>客户列表(分页)</returns>
        public async Task<PageGridData<Customer>> GetCustomerList(GetCustomerDto2 dto)
        {
            PageGridData<Customer> pageGridData = new PageGridData<Customer>();
            
            try
            {
                // 构建基础查询
                var query = _customerRepository.GetAll();
                
                // 应用查询条件
                query = query.WhereIF(!string.IsNullOrEmpty(dto.CustCode), c => c.CustCode.Contains(dto.CustCode))
                            .WhereIF(!string.IsNullOrEmpty(dto.CustName), c => c.CustName.Contains(dto.CustName))
                            .WhereIF(!string.IsNullOrEmpty(dto.CustPhone), c => c.CustPhone.Contains(dto.CustPhone))
                            .WhereIF(dto.IsEnable.HasValue, c => c.IsEnable == dto.IsEnable.Value);
                
                // 获取总记录数
                var count = await query.CountAsync();
                
                // 分页查询数据
                var data = await query.OrderBy(c => c.CustCode)
                                     .Skip((dto.PageIndex - 1) * dto.PageSize)
                                     .Take(dto.PageSize)
                                     .ToListAsync();
                
                // 构建返回数据
                pageGridData.rows = data;
                pageGridData.total = count;
                
                return pageGridData;
            }
            catch (Exception ex)
            {
                pageGridData.rows = new List<Customer>();
                pageGridData.total = 0;
                pageGridData.summary = $"获取客户列表失败：{ex.Message}";
                return pageGridData;
            }
        }

        public async Task<WebResponseContent> GetMaterialCatalogList()
        {
            WebResponseContent response = new WebResponseContent();
            
            try
            {
                // 获取所有物料分类
                var allCatalogs = await _materialCatalogRepository.GetAll()
                    .OrderBy(c => c.OrderById)
                    .ToListAsync();
                
                // 获取根级分类（ParentId = 0的分类）
                var rootCatalogs = allCatalogs
                    .Where(c => c.ParentId == 0)
                    .Select(c => new MaterialCatalogDto
                    {
                        Id = c.Id,
                        ClassifyName = c.ClassifyName,
                    })
                    .ToList();
                
                // 为每个根分类添加子分类
                foreach (var rootCatalog in rootCatalogs)
                {
                    // 获取当前根分类的子分类
                    var childCatalogs = allCatalogs
                        .Where(c => c.ParentId == rootCatalog.Id)
                        .Select(c => new MaterialCatalogDto
                        {
                            Id = c.Id,
                            ClassifyName = c.ClassifyName,
                        })
                        .ToList();
                    
                    // 添加到根分类的Children集合中
                    rootCatalog.Children.AddRange(childCatalogs);
                }
                
                // 只返回根分类（包含子分类）
                return response.OK("获取物料分类列表成功", rootCatalogs);
            }
            catch (Exception ex)
            {
                return response.Error($"获取物料分类列表失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 获取物料列表(分页)
        /// </summary>
        /// <param name="dto">查询条件</param>
        /// <returns>分页数据</returns>
        public async Task<PageGridData<MaterialProduct>> GetMaterialList(GetMaterialListDto dto)
        {
            PageGridData<MaterialProduct> pageGridData = new PageGridData<MaterialProduct>();
            
            try
            {
                // 基础查询
                var query = _materialProductRepository.GetAll();
                
                // 应用查询条件
                query = query.WhereIF(!string.IsNullOrEmpty(dto.MaterialCode), m => m.MaterialCode.Contains(dto.MaterialCode))
                           .WhereIF(!string.IsNullOrEmpty(dto.MaterialName), m => m.MaterialName.Contains(dto.MaterialName));
                
                if (!string.IsNullOrEmpty(dto.ClassifyName))
                {
                    // 联查物料分类表获取对应的分类信息
                    query = from material in query
                            join catalog in _materialCatalogRepository.GetAll()
                            on material.FlatsMaterial equals catalog.ClassifyName
                            where catalog.ClassifyName.Contains(dto.ClassifyName)
                            select material;
                }
                
                // 获取总记录数
                var count = await query.CountAsync();
                
                // 分页查询数据
                var materials = await query.OrderBy(m => m.MaterialCode)
                                         .Skip((dto.PageIndex - 1) * dto.PageSize)
                                         .Take(dto.PageSize)
                                         .ToListAsync();
                
                // 构建返回数据
                pageGridData.rows = materials;
                pageGridData.total = count;
                
                return pageGridData;
            }
            catch (Exception ex)
            {
                pageGridData.rows = new List<MaterialProduct>();
                pageGridData.total = 0;
                pageGridData.summary = $"获取物料列表失败：{ex.Message}";
                return pageGridData;
            }
        }
    }
}
